package cn.jasonone.him.controller;

import java.io.FileNotFoundException;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.jasonone.him.model.HimFriend;
import cn.jasonone.him.model.HimGroup;
import cn.jasonone.him.model.HimUserInfo;
import cn.jasonone.him.model.R;
import cn.jasonone.him.service.HimService;

@RestController
@RequestMapping("/him")
public class HimController {
	@Resource
	private HimService himService;

	/**
	 * 查询用户信息
	 * 
	 * @param userId 用户ID
	 * @return 用户信息
	 */
	@GetMapping("/list")
	public R list(String userId) {
		R r = R.success().createChild("data");
		HimUserInfo mine = himService.findMine(userId);
		if(mine == null) {
			return R.error(404, "用户不存在");
		}
		r.addItem("mine", mine);
		List<HimFriend> list = himService.findFriends(userId);
		if (list != null) {
			r.addItem("friend", list.stream().filter(f -> f != null).collect(Collectors.toList()));
		}
		List<HimGroup> groups = himService.findGroups(userId);
		if (groups != null) {
			r.addItem("group", groups.stream().filter(g -> g != null).collect(Collectors.toList()));
		}
		return r.getRoot();
	}

	/**
	 * 查询群成员列表
	 * 
	 * @param groupId 群ID
	 * @return 群成员列表
	 */
	@GetMapping("/members")
	public R members(String groupId) {
		R r = R.success().createChild("data");
		HimGroup group = himService.findGroupById(groupId);
		r.addItem("owner", group.getOwner());
		r.addItem("list", group.getList());
		return r.getRoot();
	}

	/**
	 * 上传图片
	 * 
	 * @param file 文件对象
	 * @return 上传结果
	 */
	@PostMapping("/uploadImage")
	public R uploadImage(@RequestParam("file") MultipartFile file) {
		R r = R.success().setMsg("").createChild("data");
		try {
			r.addItem("src", himService.uploadImage(file));
			return r.getRoot();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.error(500, "图片上传失败");
	}

	/**
	 * 上传文件
	 * 
	 * @param file 文件对象
	 * @return 上传结果
	 */
	@PostMapping("/uploadFile")
	public R uploadFile(@RequestParam("file") MultipartFile file) {
		R r = R.success().setMsg("").createChild("data");
		try {
			r.addItem("src", himService.uploadFile(file));
			return r.getRoot();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.error(500, "文件上传失败");
	}
}
